<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>知识库文件上传</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }
        .animate-pulse-slow {
            animation: pulse 2s infinite;
        }
        .upload-progress {
            transition: width 0.3s ease-in-out;
        }
        .fade-in {
            animation: fadeIn 0.3s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .hover-scale {
            transition: transform 0.2s ease;
        }
        .hover-scale:hover {
            transform: scale(1.02);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-12">
        <div class="max-w-2xl mx-auto">
            <!-- 标题 -->
            <div class="text-center mb-12">
                <div class="mb-4">
                    <i class="fas fa-database text-5xl text-blue-600 mb-4 animate-pulse-slow"></i>
                </div>
                <h1 class="text-4xl font-bold text-gray-800 mb-3">知识库文件上传</h1>
                <p class="text-gray-600 text-lg">快速构建您的知识库系统</p>
                <div class="flex justify-center gap-2 mt-4">
                    <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm">.md</span>
                    <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm">.txt</span>
                    <span class="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm">.sql</span>
                </div>
            </div>

            <!-- 上传表单 -->
            <div class="bg-white rounded-xl shadow-lg p-8 hover-scale">
                <form id="uploadForm" class="space-y-6">
                    <!-- 知识库名称输入 -->
                    <div>
                        <label for="ragTag" class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-tag mr-2 text-blue-500"></i>知识库名称
                        </label>
                        <input type="text" id="ragTag" name="ragTag" required
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
                            placeholder="请输入知识库名称">
                    </div>

                    <!-- 文件上传区域 -->
                    <div class="relative">
                        <div id="dropZone" 
                            class="border-3 border-dashed border-gray-300 rounded-xl p-10 text-center hover:border-blue-500 transition-all duration-300 group">
                            <input type="file" id="fileInput" multiple accept=".md,.txt,.sql" class="hidden">
                            <i class="fas fa-cloud-upload-alt text-6xl text-blue-500 mb-6 group-hover:scale-110 transition-transform duration-300"></i>
                            <div class="text-gray-600">
                                <p class="text-lg font-medium mb-2">点击或拖拽文件到此处上传</p>
                                <p class="text-sm text-gray-500">支持 .md、.txt、.sql 格式文件</p>
                            </div>
                        </div>
                    </div>

                    <!-- 文件列表 -->
                    <div id="fileList" class="space-y-3"></div>

                    <!-- 上传进度条 -->
                    <div id="uploadProgress" class="hidden">
                        <div class="h-2 bg-gray-200 rounded-full overflow-hidden">
                            <div class="upload-progress h-full bg-blue-500 w-0"></div>
                        </div>
                        <p class="text-sm text-gray-600 mt-2 text-center" id="uploadProgressText">准备上传...</p>
                    </div>

                    <!-- 上传按钮 -->
                    <div class="flex justify-end">
                        <button type="submit" 
                            class="px-8 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg hover:from-blue-700 hover:to-blue-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 transition-all duration-200 font-medium"
                            id="submitBtn">
                            <i class="fas fa-upload mr-2"></i>上传文件
                        </button>
                    </div>
                </form>
            </div>

            <!-- 上传状态提示 -->
            <div id="uploadStatus" class="mt-6 text-center hidden fade-in">
                <div class="inline-flex items-center px-6 py-3 rounded-lg text-sm shadow-md"></div>
            </div>
        </div>
    </div>

    <script>
        // API 配置
        const API_CONFIG = {
            // 使用相对路径，让 Nginx 代理处理
            BASE_URL: '',
            UPLOAD_ENDPOINT: '/api/v1/ollama/file/upload'
        };

        document.addEventListener('DOMContentLoaded', function() {
            const dropZone = document.getElementById('dropZone');
            const fileInput = document.getElementById('fileInput');
            const fileList = document.getElementById('fileList');
            const uploadForm = document.getElementById('uploadForm');
            const uploadStatus = document.getElementById('uploadStatus');
            const submitBtn = document.getElementById('submitBtn');
            const uploadProgress = document.getElementById('uploadProgress');
            const progressBar = uploadProgress.querySelector('.upload-progress');
            const progressText = document.getElementById('uploadProgressText');
            let files = [];

            // 点击上传区域触发文件选择
            dropZone.addEventListener('click', () => fileInput.click());

            // 处理拖拽事件
            dropZone.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropZone.classList.add('border-blue-500', 'bg-blue-50');
            });

            dropZone.addEventListener('dragleave', () => {
                dropZone.classList.remove('border-blue-500', 'bg-blue-50');
            });

            dropZone.addEventListener('drop', (e) => {
                e.preventDefault();
                dropZone.classList.remove('border-blue-500', 'bg-blue-50');
                handleFiles(e.dataTransfer.files);
            });

            // 处理文件选择
            fileInput.addEventListener('change', (e) => {
                handleFiles(e.target.files);
            });

            function handleFiles(newFiles) {
                const validTypes = ['.md', '.txt', '.sql'];
                Array.from(newFiles).forEach(file => {
                    const extension = '.' + file.name.split('.').pop().toLowerCase();
                    if (validTypes.includes(extension)) {
                        if (!files.some(f => f.name === file.name)) {
                            files.push(file);
                            displayFile(file);
                        } else {
                            showStatus(`文件 ${file.name} 已存在`, 'warning');
                        }
                    } else {
                        showStatus(`不支持的文件类型: ${file.name}`, 'error');
                    }
                });
            }

            function getFileIcon(fileName) {
                const extension = fileName.split('.').pop().toLowerCase();
                switch(extension) {
                    case 'md': return '<i class="fas fa-file-alt text-blue-500"></i>';
                    case 'txt': return '<i class="fas fa-file-text text-green-500"></i>';
                    case 'sql': return '<i class="fas fa-database text-purple-500"></i>';
                    default: return '<i class="fas fa-file text-gray-500"></i>';
                }
            }

            function displayFile(file) {
                const fileDiv = document.createElement('div');
                fileDiv.className = 'flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors duration-200 fade-in';
                fileDiv.innerHTML = `
                    <div class="flex items-center space-x-3">
                        ${getFileIcon(file.name)}
                        <span class="text-sm font-medium text-gray-700">${file.name}</span>
                        <span class="text-xs text-gray-500">${formatFileSize(file.size)}</span>
                    </div>
                    <button type="button" class="text-red-500 hover:text-red-700 transition-colors duration-200">
                        <i class="fas fa-times-circle text-lg"></i>
                    </button>
                `;

                fileDiv.querySelector('button').addEventListener('click', () => {
                    fileDiv.classList.add('fade-out');
                    setTimeout(() => {
                        files = files.filter(f => f !== file);
                        fileDiv.remove();
                    }, 300);
                });

                fileList.appendChild(fileDiv);
            }

            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            function updateProgress(percent) {
                progressBar.style.width = `${percent}%`;
                progressText.textContent = `上传进度: ${percent}%`;
            }

            function resetUploadForm() {
                files = [];
                fileList.innerHTML = '';
                fileInput.value = '';
                uploadProgress.classList.add('hidden');
                progressBar.style.width = '0%';
            }

            // 处理表单提交
            uploadForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const ragTag = document.getElementById('ragTag').value.trim();
                
                if (!ragTag) {
                    showStatus('请输入知识库名称', 'error');
                    return;
                }

                if (files.length === 0) {
                    showStatus('请选择要上传的文件', 'error');
                    return;
                }

                submitBtn.disabled = true;
                uploadProgress.classList.remove('hidden');
                showStatus('正在上传...', 'loading');

                const formData = new FormData();
                formData.append('ragTag', ragTag);
                files.forEach(file => {
                    formData.append('file', file);
                });

                let progressInterval;
                try {
                    // 模拟上传进度
                    let progress = 0;
                    progressInterval = setInterval(() => {
                        progress += Math.random() * 30;
                        if (progress > 90) clearInterval(progressInterval);
                        updateProgress(Math.min(90, Math.round(progress)));
                    }, 500);

                    const url = `${API_CONFIG.BASE_URL}${API_CONFIG.UPLOAD_ENDPOINT}`;
                    console.log('Uploading to:', url);

                    const response = await fetch(url, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'Accept': 'application/json'
                        },
                        credentials: 'include',
                        mode: 'cors'
                    });

                    clearInterval(progressInterval);

                    if (!response.ok) {
                        const errorText = await response.text();
                        throw new Error(`服务器响应错误 (${response.status}): ${errorText}`);
                    }

                    const result = await response.json();
                    
                    if (result.code === '0000') {
                        updateProgress(100);
                        showStatus('上传成功！', 'success');
                        // 清空表单
                        resetUploadForm();
                        document.getElementById('ragTag').value = '';
                        setTimeout(() => {
                            uploadProgress.classList.add('hidden');
                            progressBar.style.width = '0%';
                        }, 1000);
                    } else {
                        throw new Error(result.info || '上传失败');
                    }
                } catch (error) {
                    console.error('Upload error:', error);
                    clearInterval(progressInterval);
                    resetUploadForm();
                    
                    let errorMessage = '上传失败';
                    if (error.message.includes('Failed to fetch')) {
                        errorMessage = '无法连接到服务器，请检查网络连接或服务器状态';
                    } else if (error.message.includes('NetworkError')) {
                        errorMessage = '网络错误，请检查网络连接';
                    } else if (error.message.includes('服务器响应错误')) {
                        errorMessage = error.message;
                    }
                    
                    showStatus(errorMessage, 'error');
                } finally {
                    submitBtn.disabled = false;
                }
            });

            function showStatus(message, type) {
                const statusDiv = uploadStatus.querySelector('div');
                uploadStatus.classList.remove('hidden');
                
                let bgColor = '';
                let icon = '';
                
                switch(type) {
                    case 'success':
                        bgColor = 'bg-green-100 text-green-700 border border-green-200';
                        icon = '<i class="fas fa-check-circle mr-2"></i>';
                        break;
                    case 'error':
                        bgColor = 'bg-red-100 text-red-700 border border-red-200';
                        icon = '<i class="fas fa-exclamation-circle mr-2"></i>';
                        break;
                    case 'warning':
                        bgColor = 'bg-yellow-100 text-yellow-700 border border-yellow-200';
                        icon = '<i class="fas fa-exclamation-triangle mr-2"></i>';
                        break;
                    case 'loading':
                        bgColor = 'bg-blue-100 text-blue-700 border border-blue-200';
                        icon = '<i class="fas fa-spinner fa-spin mr-2"></i>';
                        break;
                }

                statusDiv.className = `inline-flex items-center px-6 py-3 rounded-lg text-sm ${bgColor}`;
                statusDiv.innerHTML = icon + message;

                if (type !== 'loading') {
                    setTimeout(() => {
                        uploadStatus.classList.add('hidden');
                    }, 3000);
                }
            }
        });
    </script>
</body>
</html> 